#include "Communications_Handler.h"

uint8 u8IIC_TxBuffer [IIC_TX_BUFFER_SIZE] = { "ABCDEFGHIJ" };
uint8 u8IIC_TxCount;

static uint8 u8IIC_Temp;

void vfnComm_BuildIICPacket (void)
{
    
}

void vfnIIC_Init (void)
{
    vfnIIC_SetAddress (0xCC);
    vfnIIC_BaudRate (IIC_BAUDRATE_100KBPS);
    vfnIIC_ModuleStatus (IIC_MODULE_ENABLED);
    vfnIIC_InterruptStatus (IIC_INTERRUPTS_ENABLED);
}

void vfnIIC_SlaveReadWrite (void) 
{
    if (u8IIC_SlaveStatus())   // Check for Slave Receive or transmit
    {     
        vfnIIC_DataDirection (IIC_TRANSMIT);// Set Tx bit to begin a Transmit
        vfnIIC_SendData (u8IIC_TxBuffer[u8IIC_TxCount]);
        u8IIC_TxCount++;
    } 
    else 
    {
        vfnIIC_DataDirection (IIC_RECEIVE); // Switch to RX mode
        (void)u8IIC_ReadData();            // Dummy read from Data Register    
    }
}


void vfnIIC_SlaveReadStore (void) 
{
    u8IIC_Temp = u8IIC_ReadData();
}


interrupt 17 void IIC_ISR (void)   // IIC interrupt vector number = 17 (S08) 
{                                                                             
    vfnIIC_ClearInterruptFlag();   // Clear Interrupt Flag
    
    if (!u8IIC_MasterMode())       // Slave?  nomas pa chekar... no vaya a ser
    { 

        if (u8IIC_CheckIfAdressed()) 
        {                
            u8IIC_TxCount = 0;
            vfnIIC_SlaveReadWrite();
        }
        else 
        {
            if (u8IIC_TransmitMode())  // Check for ACK received
            {                
                if (!u8IIC_AckReceived())    // ACK Recieved
                {             
                    vfnIIC_SendData (u8IIC_TxBuffer[u8IIC_TxCount]);
                    u8IIC_TxCount++;;
           
                }
                else 
                {
                    vfnIIC_DataDirection (IIC_RECEIVE); // Switch to RX mode
                    (void)u8IIC_ReadData ();            // Dummy read from Data Register
                }
            } 
            else 
            {
                vfnIIC_SlaveReadStore();
            }
        }
    }
}


